<template>
	<el-container>
		<el-header>
			<div class="left-panel">
				<el-button type="primary" icon="el-icon-plus" @click="add"></el-button>
				<el-button type="danger" plain icon="el-icon-delete" :disabled="selection.length == 0" @click="batch_del"></el-button>
			</div>
			<div class="right-panel">
				<div class="right-panel-search">
					<el-input v-model="search.name" :placeholder="$t('platform.name')" clearable style="width: 150px"></el-input>
					<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding">
			<scTable ref="table" :apiObj="apiObj" row-key="id" @selection-change="selectionChange" hideSetting border stripe size="small" style="width: 100%">
				<el-table-column type="selection" width="50"></el-table-column>
				<el-table-column :label="$t('platform.name')" prop="name" width="120" align="center"></el-table-column>
				<el-table-column :label="$t('common.describe')" prop="describe" :header-align="'center'"></el-table-column>
				<el-table-column :label="$t('common.status')" prop="status" width="80" align="center">
					<template #default="scope">
						<el-switch v-model="scope.row.status" @change="changeSwitch($event, scope.row)" :loading="scope.row.$switch_status" :active-value="1" :inactive-value="0"></el-switch>
					</template>
				</el-table-column>
				<el-table-column :label="$t('common.handle')" fixed="right" align="center" width="170">
					<template #default="scope">
						<el-button-group>
							<el-button text type="primary" size="small" @click="table_edit(scope.row)">{{ $t('common.edit') }}</el-button>
							<el-popconfirm :title="$t('common.askDel')" @confirm="table_del(scope.row)">
								<template #reference>
									<el-button text type="primary" size="small">{{ $t('common.del') }}</el-button>
								</template>
							</el-popconfirm>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
	</el-container>
	<saveDialog v-if="saveVisible" ref="saveRef" @success="handleSaveSuccess" @closed="saveVisible = false"></saveDialog>
</template>
<script setup lang="ts">
	// 引入异步组件 saveDialog，用于保存数据时显示的弹窗
	const saveDialog = defineAsyncComponent(() => import('./save.vue'))
	// 保存选中的表格行数据
	const selection = ref<any>([])
	// 搜索框的绑定数据，初始为 null
	const search = reactive({ name: null })
	// 配置表格数据接口
	const apiObj = ref(api.platform.list)
	// 控制 saveDialog 的显示与隐藏
	const saveVisible = ref(false)
	// 保存 saveDialog 的引用，便于在组件内调用方法
	const saveRef = ref<any>(null)
	// 表格的引用，用于刷新表格数据
	const table = ref<any>(null)
	// 当前选中的行，用于编辑操作
	const currentRow = ref<any>(null)
	// 添加按钮点击事件，打开 saveDialog 并重置当前行
	const add = async () => ((currentRow.value = null), (saveVisible.value = true))
	// 批量删除选中行数据
	const batch_del = () => {
		// 显示删除确认框
		ElMessageBox.confirm(lang.global.t('common.confirmDelete', { count: selection.value.length }), lang.global.t('common.tip'), {
			type: 'warning'
		}).then(async () => {
			// 获取选中行的 ID 列表
			const ids = selection.value.map((item: { id: number }) => item.id)
			// 调用删除接口，删除选中的数据
			const res = await api.platform.del.delete({ id: ids })
			if (res.code === 200) {
				// 刷新表格数据
				table.value.refresh()
				ElMessage.success(res.message)
			} else {
				ElMessage.error(res.message)
			}
		})
	}
	// 执行搜索操作，根据搜索条件刷新表格数据
	const upsearch = () => table.value.upData(search)
	// 表格选中项改变时触发，将选中的数据保存在 selection 中
	const selectionChange = (val: string[]) => (selection.value = val)
	// 表格行编辑操作，打开 saveDialog 并设置当前编辑行的数据
	const table_edit = (row: any) => ((currentRow.value = row), (saveVisible.value = true))
	// 表格行删除操作，删除指定行的数据
	const table_del = async (row: { id: number }) => {
		const res = await api.platform.del.delete({ id: [row.id] })
		if (res.code === 200) {
			// 刷新表格数据
			table.value.refresh()
			ElMessage.success(res.message)
		} else {
			ElMessage.error(res.message)
		}
	}
	// 切换行的状态（启用或禁用）
	const changeSwitch = async (val: any, row: any) => {
		row.status = row.status === 0 ? 0 : 1
		row.$switch_status = true
		// 调用状态接口更新数据
		const status = await api.platform.state.put({ id: row.id, status: row.status })
		if (status.code === 200) {
			// 成功后更新行状态
			setTimeout(() => {
				delete row.$switch_status
				row.status = val
				ElMessage.success(status.message)
			}, 500)
		} else {
			ElMessage.error(status.message)
		}
	}
	// 处理 saveDialog 成功保存后的回调，刷新表格数据
	const handleSaveSuccess = () => table.value.refresh()
	// 监听 saveRef 变化，当 saveRef 存在时，根据 currentRow 判断弹窗模式（新增或编辑）
	watch(saveRef, () => {
		if (currentRow.value) {
			// 编辑模式
			saveRef.value?.open('edit')
			saveRef.value?.setData(currentRow.value)
		} else {
			// 新增模式
			saveRef.value?.open('add')
		}
	})
</script>
